package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	_ "mysql-master"
	"net"
	"net/http"
	"strings"
	"sync/atomic"
	"websocket-master"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	http.HandleFunc("/ws", handleConnections)

	log.Println("WebSocket服务器启动，监听8081端口...")
	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ws.Close()

	var shouldContinue int32 = 1
	done := make(chan bool)

	go receiveFromTCPServer(ws, &shouldContinue, done)
	<-done // 等待任一 Goroutine 完成
	atomic.StoreInt32(&shouldContinue, 0)

}

func receiveFromTCPServer(ws *websocket.Conn, shouldContinue *int32, done chan bool) {
	defer func() { done <- true }()
	tcpServerAddr := "192.168.43.96:5050" // TCP 服务器地址
	log.Println("尝试连接到TCP服务器:", tcpServerAddr)
	tcpConn, err := net.Dial("tcp", tcpServerAddr)
	if err != nil {
		log.Fatal("连接到TCP服务器错误:", err)
	}
	defer tcpConn.Close()
	log.Println("成功连接到TCP服务器")

	for atomic.LoadInt32(shouldContinue) == 1 {
		log.Println("等待从TCP服务器读取数据...")
		_, msg, readerr := ws.ReadMessage()
		if readerr != nil {
			log.Println("读取消息错误:", readerr)
			break
		}
		var data map[string]interface{}
		err := json.Unmarshal(msg, &data)
		if err != nil {
			log.Println("解析WebSocket消息错误:", err)
			//return
		}

		// 将所有值转换为字符串
		strData := make(map[string]string)
		for k, v := range data {
			switch v := v.(type) {
			case string:
				strData[k] = v
			case bool, int, float64, nil:
				strData[k] = fmt.Sprintf("%v", v)
			case []interface{}:
				// 对数组进行处理，将每个元素转换为字符串
				arrayStr := make([]string, len(v))
				for i, val := range v {
					arrayStr[i] = fmt.Sprintf("%v", val)
				}
				strData[k] = fmt.Sprintf("[%s]", strings.Join(arrayStr, ", "))
			case map[string]interface{}:
				// 对对象进行递归处理
				var m map[string]string
				err := json.Unmarshal([]byte(fmt.Sprintf("%v", v)), &m)
				if err != nil {
					log.Println("递归转换JSON对象为字符串错误:", err)
					return
				}
				strData[k] = fmt.Sprintf("%v", m)
			default:
				// 对于未知类型，尝试直接转换
				strData[k] = fmt.Sprintf("%v", v)
			}
		}
		log.Println("收到来自tcp服务器的数据:", strData)
		//jsonData, err := json.Marshal(strData)
		if err != nil {
			log.Println("将strData转换为JSON时出错:", err)
			// 处理错误，例如：返回，或尝试再次发送
		}
		hasAction := false
		for key := range strData {
			if key == "action" {
				hasAction = true
				break
			}
		}
		if hasAction {
			action := strData["action"]
			var data1 string
			var err1 error
			switch action {
			case "queryDeviceRegistration":
				data1, err1 = queryTableFromDatabase("device_registration")
				err = ws.WriteMessage(websocket.TextMessage, []byte(data1))
				if err != nil {
					log.Println("发送消息错误:", err)
					break
				}
			case "queryDeviceAttributes":
				data1, err1 = queryTableFromDatabase("device_attributes")
				err = ws.WriteMessage(websocket.TextMessage, []byte(data1))
				if err != nil {
					log.Println("发送消息错误:", err)
					break
				}
			case "queryRealTimeData":
				data1, err1 = queryTableFromDatabase("real_time_data")
				err = ws.WriteMessage(websocket.TextMessage, []byte(data1))
				if err != nil {
					log.Println("发送消息错误:", err)
					break
				}
			case "queryLiftingData":
				data1, err1 = queryTableFromDatabase("lifting_data")
				err = ws.WriteMessage(websocket.TextMessage, []byte(data1))
				//log.Println([]byte(data1))
				if err != nil {
					log.Println("发送消息错误:", err)
					break
				}
			default:
				data1 = "未知操作"
				err1 = fmt.Errorf("未知操作: %s", action)
				if err1 != nil {
					log.Println("数据库操作错误:", err)
					data1 = "数据库操作错误: " + err.Error()
				}
			}
		} else {
			interfaceData := make(map[string]interface{})
			for k, v := range strData {
				interfaceData[k] = v // 这里假设 strData 中的值可以直接转换为 interface{}
			}
			jsonData, err := json.Marshal(interfaceData)
			if err != nil {
				log.Println("将 interfaceData 转换为 JSON 时出错:", err)
				// 处理错误，例如：返回，或尝试再次发送
			}
			jsonBytes := string(jsonData)
			//		log.Println("发送消息:", []byte(jsonBytes))
			err = ws.WriteMessage(websocket.TextMessage, []byte(jsonBytes))
			log.Println("发送成功")
			if err != nil {
				log.Println("发送TCP服务器消息错误:", err)
				atomic.StoreInt32(shouldContinue, 0)
			}
		}
		// 将JSON字符串转换为字节切片

	}
	done <- true
}

func queryTableFromDatabase(tableName string) (string, error) {
	dsn := "remote_user:password@tcp(192.168.43.96:3306)/db2"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return "", err
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		return "", err
	}

	rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s", tableName))
	if err != nil {
		return "", err
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		return "", err
	}

	results := make([]map[string]interface{}, 0)
	for rows.Next() {
		columnsData := make([]interface{}, len(columns))
		columnPointers := make([]interface{}, len(columns))
		for i := range columnsData {
			columnPointers[i] = &columnsData[i]
		}

		if err := rows.Scan(columnPointers...); err != nil {
			return "", err
		}

		rowData := make(map[string]interface{})
		for i, colName := range columns {
			val := columnPointers[i].(*interface{})
			rowData[colName] = *val
		}

		results = append(results, rowData)
	}

	if err = rows.Err(); err != nil {
		return "", err
	}

	jsonData, err := json.Marshal(results)
	if err != nil {
		return "", err
	}

	return string(jsonData), nil
}
